//
//  SZLSureSingleViewController.m
//  Shengzhuli
//
//  Created by 卡忙科技 on 16/8/7.
//  Copyright © 2016年 kamangkeji. All rights reserved.
//

#import "SZLSureSingleViewController.h"
#import "ReceiveTableViewCell.h"
#import "CarGooodsTableViewCell.h"
#import "SingleSelectTableViewCell.h"
#import "SZLReceiveAddressViewController.h"
#import "SZLSinglePayViewController.h"
#import "ReceiveAddressNetwork.h"
#import "SingleNetService.h"
#import "SZLAccountHelper.h"
#import <Masonry.h>
#import "MBProgressHUD+MJ.h"
#import "BuyCarModel.h"
#import "CarShopHeaderView.h"
#import "CarShopFooterView.h"
#import "ScoreSelectCell.h"
#import "SZLSingleListViewController.h"

@interface SZLSureSingleViewController ()<UITableViewDataSource,UITableViewDelegate,SingleSelectTableViewCellDelegate,CarGooodsTableViewCellDelegate,CarShopHeaderViewDelegate>

@property (nonatomic,strong) UITableView *sourceTab;
@property (nonatomic,weak) UIView *toolBar;
@property (nonatomic,assign) BOOL isNeedPickSelf;//是否需要自提
@property (nonatomic,assign) BOOL isNeedRise;//是否需要发票
@property (nonatomic,strong) AddressModel *model;//收货地址
@property (nonatomic,copy) NSString *riseString;//发票
@property (nonatomic,weak) UILabel *allMoney;//合计
@property (nonatomic,assign) BOOL isUseScore;//是否使用积分

@end

@implementation SZLSureSingleViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.navigationItem.title = @"确认订单";
    self.isUseScore = YES;
    [self getDefaultAddress];
}
- (void)setView
{
    [self.view addSubview:self.sourceTab];
    UIView *toolBar = [[UIView alloc]initWithFrame:CGRectMake(0, ScreenH-64-50, ScreenW, 50)];
    toolBar.backgroundColor = RGBColorA(247, 247, 247, 0.95);
    [self.view addSubview:toolBar];
    UIView *lineView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenW, 0.7)];
    lineView.backgroundColor = RGBColorOne(210);
    [toolBar addSubview:lineView];
    
    UILabel *allMoney = [[UILabel alloc]initWithFrame:CGRectMake(10, 15, ScreenW-120-20, 20)];
    allMoney.textColor = [UIColor redColor];
    allMoney.font = FontB(16);
    allMoney.textAlignment = NSTextAlignmentRight;
    allMoney.text = [NSString stringWithFormat:@"实付款:¥%.2f",[self calculateRealMoney]];
    self.allMoney = allMoney;
    [toolBar addSubview:allMoney];
    
    UIButton *sureBtn = [[UIButton alloc]initWithFrame:CGRectMake(ScreenW-120, 0, 120 , 50)];
    [sureBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    sureBtn.titleLabel.font = FontB(18);
    sureBtn.backgroundColor = [UIColor redColor];
    [sureBtn setTitle:@"提交订单" forState:UIControlStateNormal];
    [sureBtn addTarget:self action:@selector(sureClick) forControlEvents:UIControlEventTouchUpInside];
    [toolBar addSubview:sureBtn];
    self.toolBar = toolBar;
}
- (void)sureClick
{
    [self.view endEditing:YES];
    if (self.model.receiveAddress.length<1){
        [MBProgressHUD showError:@"请先选择收货地址" toView:self.view];
        return;
    }
    [self createSingle];
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 0 || section == self.payModels.count+1) {
        return 10;
    }
    return 50;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    if (section == 0 || section == self.payModels.count+1) {
        return 0.01;
    }
    return 40;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        return 75;
    }else if (indexPath.section == self.payModels.count+1){
        return 50;
    }
    return 150;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.payModels.count+2;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0 || section == self.payModels.count+1) {
        return 1;
    }
    BuyCarModel *model = self.payModels[section-1];
    return model.productList.count;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (section == 0 || section == self.payModels.count+1) {
        return nil;
    }
    BuyCarModel *carModel = self.payModels[section-1];
    if (carModel.productList.count<1) return nil;
    CarShopHeaderView *header = [tableView dequeueReusableHeaderFooterViewWithIdentifier:NSStringFromClass([CarShopHeaderView class])];
    header.model = carModel;
    header.isSureSingle = YES;
    header.delegate = self;
    return header;
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    if (section == 0 || section == self.payModels.count+1) {
        return nil;
    }
    BuyCarModel *carModel = self.payModels[section-1];
    if (carModel.productList.count<1) return nil;
    CarShopFooterView *header = [tableView dequeueReusableHeaderFooterViewWithIdentifier:NSStringFromClass([CarShopFooterView class])];
    header.model = carModel;
    return header;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        ReceiveTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([ReceiveTableViewCell class])];
        cell.clipsToBounds = YES;
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        cell.model = self.model;
        return cell;
    }else if (indexPath.section == self.payModels.count+1){
        ScoreSelectCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([ScoreSelectCell class])];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        BuyCarModel *carModel = self.payModels[0];
        NormalShopGoodsModel *model = carModel.productList[0];
        cell.score = model.total;
        __WEAK
        cell.switchBlock = ^(BOOL isOn) {
            self.isUseScore = isOn;
            float real = [self calculateRealMoney];
            weakSelf.allMoney.text = [NSString stringWithFormat:@"实付款:¥%.2f",real];
        };
        return cell;
    }
    CarGooodsTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([CarGooodsTableViewCell class])];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    BuyCarModel *carModel = self.payModels[indexPath.section-1];
    cell.model = carModel.productList[indexPath.row];
    cell.isNeedsHidden = YES;
    cell.delegate = self;
    return cell;
}
#pragma mark -----------SingleSelectTableViewCellDelegate--------------------
- (void)singleSelectTableViewCellNeedsPickSelf:(BOOL)isNeedPickSelf
{
    self.isNeedPickSelf = isNeedPickSelf;
    self.allMoney.text = [NSString stringWithFormat:@"实付款:¥%.2f",[self getGoodsMoney]+[self getFreightMoney]];
    [self.sourceTab beginUpdates];
    [self.sourceTab reloadData];
    [self.sourceTab endUpdates];
}
- (void)singleSelectTableViewCellNeedRise:(BOOL)isNeedRise
{
    self.isNeedRise = isNeedRise;
    [self.sourceTab reloadData];
    [self.sourceTab scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:2] atScrollPosition:UITableViewScrollPositionBottom animated:YES];
}

#pragma mark -------------------------------------------------
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.section == 0) {
        SZLReceiveAddressViewController *receiveVc = [[SZLReceiveAddressViewController alloc]init];
        receiveVc.type = AddressTypeSelect;
        __weak typeof(self)weakSelf = self;
        receiveVc.selectBlock = ^(AddressModel *model){
            weakSelf.model = model;
            [weakSelf.sourceTab reloadSections:[NSIndexSet indexSetWithIndex:0] withRowAnimation:UITableViewRowAnimationAutomatic];
        };
        [self.navigationController pushViewController:receiveVc animated:YES];
    }
}
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
        [cell setSeparatorInset:UIEdgeInsetsZero];
    }
    
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
}
-(void)viewDidLayoutSubviews
{
    if ([self.sourceTab respondsToSelector:@selector(setSeparatorInset:)]) {
        [self.sourceTab setSeparatorInset:UIEdgeInsetsZero];
    }
    
    if ([self.sourceTab respondsToSelector:@selector(setLayoutMargins:)]) {
        [self.sourceTab setLayoutMargins:UIEdgeInsetsZero];
    }
}

- (void)addObserve
{
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(frameChanged:) name:UIKeyboardDidChangeFrameNotification object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(textFieldChTextanged:) name:UITextFieldTextDidChangeNotification object:nil];
}
//键盘事件
- (void)frameChanged:(NSNotification *)noti
{
    CGRect endRect = [noti.userInfo[@"UIKeyboardFrameEndUserInfoKey"] CGRectValue];
    [self.toolBar mas_updateConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.view).mas_offset(endRect.origin.y-ScreenH);
    }];
    [UIView animateWithDuration:0.05 animations:^{
        [self.view setNeedsLayout];
    }];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.01 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self.sourceTab scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:2] atScrollPosition:UITableViewScrollPositionBottom animated:YES];
    });
}
//textfield事件
- (void)textFieldChTextanged:(NSNotification *)noti
{
    UITextField *riseField = noti.object;
    self.riseString = riseField.text;
}
- (UITableView *)sourceTab
{
    if (!_sourceTab) {
        _sourceTab = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, ScreenW, ScreenH-64) style:UITableViewStyleGrouped];
        _sourceTab.delegate = self;
        _sourceTab.dataSource = self;
        _sourceTab.contentInset = UIEdgeInsetsMake(0, 0, 50, 0);
        [_sourceTab registerNib:[UINib nibWithNibName:NSStringFromClass([ReceiveTableViewCell class]) bundle:nil] forCellReuseIdentifier:NSStringFromClass([ReceiveTableViewCell class])];
        [_sourceTab registerNib:[UINib nibWithNibName:NSStringFromClass([CarGooodsTableViewCell class]) bundle:nil] forCellReuseIdentifier:NSStringFromClass([CarGooodsTableViewCell class])];
        [_sourceTab registerClass:[CarShopHeaderView class] forHeaderFooterViewReuseIdentifier:NSStringFromClass([CarShopHeaderView class])];
        [_sourceTab registerClass:[CarShopFooterView class] forHeaderFooterViewReuseIdentifier:NSStringFromClass([CarShopFooterView class])];
        [_sourceTab registerNib:[UINib nibWithNibName:NSStringFromClass([ScoreSelectCell class]) bundle:nil] forCellReuseIdentifier:NSStringFromClass([ScoreSelectCell class])];
    }
    return _sourceTab;
}
#pragma mark ---------------请求相关-------------------
- (void)createSingle
{
    NSMutableDictionary *parame = [NSMutableDictionary dictionary];
    parame[@"token"] = [SZLAccountHelper shareInstance].token;
    parame[@"productNos"] = [[self getProductNos] componentsJoinedByString:@"#"];
    parame[@"productCounts"] = [[self getProductCounts] componentsJoinedByString:@"#"];
    parame[@"receiveAddressId"] = @(self.model.ID);
    parame[@"freight"] = @([self getFreightMoney]);
    if (self.isUseScore) {
        BuyCarModel *carModel = self.payModels[0];
        NormalShopGoodsModel *model = carModel.productList[0];
        parame[@"exchange"] = @(model.total);
    }else{
        parame[@"exchange"] = @(0);
    }
    __WEAK
    [self showWaiter];
    [SingleNetService createSingleParame:parame response:^(BOOL success, NSString *msg, SingleCreateModel *model) {
        [self hideWaiter];
        if (success) {
            if (model.sumPrice == 0) {
                [MBProgressHUD showSuccess:@"支付成功"];
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    SZLSingleListViewController *listVc = [[SZLSingleListViewController alloc]init];
                    listVc.type = SingleTypeReadyDeliver;
                    listVc.isFromPay = YES;
                    listVc.model = model;
                    [weakSelf.navigationController pushViewController:listVc animated:YES];
                });
                return ;
            }
            SZLSinglePayViewController *payVc = [[SZLSinglePayViewController alloc]init];
            payVc.payChargeType = PayChargeTypeSingle;
            payVc.model = model;
            [self.navigationController pushViewController:payVc animated:YES];
        }else{
            [MBProgressHUD showError:msg toView:self.view];
        }
    }];
}
- (void)getDefaultAddress
{
    NSMutableDictionary *parame = [NSMutableDictionary dictionary];
    parame[@"token"] = [SZLAccountHelper shareInstance].token;
    [self showWaiter];
    [ReceiveAddressNetwork getDefaultAddressWithParame:parame response:^(BOOL success, NSString *msg, AddressModel *model) {
        [self hideWaiter];
        self.model = model;
        [self setView];
    }];
}
#pragma MARK ---------请求需要获取的参数---------------------
- (float)getGoodsMoney
{
    float allMoney = 0;
    for (BuyCarModel *buyModel in self.payModels) {
        for (NormalShopGoodsModel *goodsModel in buyModel.productList) {
            allMoney += goodsModel.price*goodsModel.productInShopCarCount;
        }
    }
    return allMoney;
}
- (float)getFreightMoney
{
    float allMoney = 0;
    for (BuyCarModel *buyModel in self.payModels) {
        allMoney += buyModel.freight;
    }
    return allMoney;
}
//获取订单号列表
- (NSArray *)getProductNos
{
    NSMutableArray *nos = [NSMutableArray array];
    for (BuyCarModel *buyModel in self.payModels) {
        for (NormalShopGoodsModel *goodsModel in buyModel.productList) {
            [nos addObject:goodsModel.productNo];
        }
    }
    return nos;
}
//获取数量列表
- (NSArray *)getProductCounts
{
    NSMutableArray *counts = [NSMutableArray array];
    for (BuyCarModel *buyModel in self.payModels) {
        for (NormalShopGoodsModel *goodsModel in buyModel.productList) {
            [counts addObject:@(goodsModel.productInShopCarCount)];
        }
    }
    return counts;
}
//计算实付款
- (float)calculateRealMoney
{
    float goodsMoney = [self getGoodsMoney];
    float freight = [self getFreightMoney];
    float real = goodsMoney + freight;
    if (self.isUseScore) {
        BuyCarModel *carModel = self.payModels[0];
        NormalShopGoodsModel *model = carModel.productList[0];
        float score = model.total;
        if (score >= real) {
            real = 0;
        }else {
            real -= score;
        }
    }
    return real;
}
- (void)dealloc
{
    [[NSNotificationCenter defaultCenter]removeObserver:self name:UIKeyboardDidChangeFrameNotification object:nil];
    [[NSNotificationCenter defaultCenter]removeObserver:self name:UITextFieldTextDidChangeNotification object:nil];
}

@end
